<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const activeStatus = ref('0')
const approveList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框相关
const detailDialogVisible = ref(false)
const detailDialogTitle = ref('')
const currentDetailType = ref('')
const applyDetails = ref([])
const repairDetail = ref({})
const vehicleDetail = ref({})

// 获取审批单列表
const getApproveList = async () => {
  loading.value = true
  try {
    const response = await axios.get('/carRepair/admin/partManage/repairPartApprove', {
      params: {
        approveStatus: activeStatus.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      approveList.value = response.data.data.records
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取审批单列表失败:', error)
    ElMessage.error('获取审批单列表失败')
  } finally {
    loading.value = false
  }
}

// 处理状态变化
const handleStatusChange = (status) => {
  activeStatus.value = status
  currentPage.value = 1
  getApproveList()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getApproveList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getApproveList()
}

// 处理审批
const handleApprove = async (row, status) => {
  try {
    await ElMessageBox.confirm(
      `确定要${status === 1 ? '通过' : '拒绝'}这个申请吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await axios.put('/carRepair/admin/partManage/repairPartApprove', {
      applyId: row.applyId,
      approveStatus: status
    })
    
    if (response.data.code === 200) {
      ElMessage.success('操作成功')
      getApproveList()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 处理查看详情
const handleViewDetail = async (row) => {
  if (!row.detailType) {
    ElMessage.warning('请选择要查看的详情类型')
    return
  }

  currentDetailType.value = row.detailType
  detailDialogVisible.value = true

  try {
    switch (row.detailType) {
      case 'apply':
        detailDialogTitle.value = '申请明细'
        const applyResponse = await axios.get(`/carRepair/admin/partManage/repairPartApprove/${row.applyId}`)
        if (applyResponse.data.code === 200) {
          applyDetails.value = applyResponse.data.data
        }
        break
      case 'repair':
        detailDialogTitle.value = '工单明细'
        const repairResponse = await axios.get(`/carRepair/admin/partManage/repairOrder/${row.repairId}`)
        if (repairResponse.data.code === 200) {
          repairDetail.value = repairResponse.data.data
        }
        break
      case 'vehicle':
        detailDialogTitle.value = '车辆信息'
        const vehicleResponse = await axios.get(`/carRepair/admin/partManage/repairVehicle/${row.vehicleId}`)
        if (vehicleResponse.data.code === 200) {
          vehicleDetail.value = vehicleResponse.data.data
        }
        break
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

onMounted(() => {
  getApproveList()
})
</script>

<template>
  <div class="repair-approve">
    <!-- 审批状态菜单 -->
    <el-card class="status-menu">
      <el-menu
        :default-active="activeStatus"
        mode="horizontal"
        @select="handleStatusChange"
      >
        <el-menu-item index="0">未审批</el-menu-item>
        <el-menu-item index="1">已审批</el-menu-item>
        <el-menu-item index="-1">已拒绝</el-menu-item>
      </el-menu>
    </el-card>

    <!-- 审批单表格 -->
    <el-card class="approve-table">
      <el-table
        :data="approveList"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="applyId" label="申请ID" width="120"></el-table-column>
        <el-table-column prop="repairId" label="维修工单ID" width="120"></el-table-column>
        <el-table-column prop="employeeName" label="领用人" width="100"></el-table-column>
        <el-table-column prop="customerName" label="客户姓名" width="100"></el-table-column>
        <el-table-column prop="applyQuantity" label="申请数量" width="80"></el-table-column>
        <el-table-column prop="applyAmount" label="申请金额" width="80">
          <template #default="scope">
            ¥{{ scope.row.applyAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="applyDatetime" label="申请时间" width="160"></el-table-column>
        <el-table-column label="详情" width="200">
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-select v-model="scope.row.detailType" placeholder="请选择" size="small">
                <el-option label="申请明细" value="apply"></el-option>
                <el-option label="工单明细" value="repair"></el-option>
                <el-option label="车辆信息" value="vehicle"></el-option>
              </el-select>
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(scope.row)"
              >
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <template v-if="activeStatus === '0'">
              <el-button
                type="success"
                size="small"
                @click="handleApprove(scope.row, 1)"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleApprove(scope.row, -1)"
              >
                拒绝
              </el-button>
            </template>
            <template v-else>
              <span>审批时间：{{ scope.row.approveDatetime }}</span>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailDialogTitle"
      width="50%"
    >
      <!-- 申请明细 -->
      <template v-if="currentDetailType === 'apply'">
        <el-table :data="applyDetails" style="width: 100%">
          <el-table-column label="零件图片" width="120">
            <template #default="scope">
              <el-image
                style="width: 80px; height: 80px"
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
          <el-table-column prop="partTypeName" label="零件类型名称"></el-table-column>
          <el-table-column prop="partName" label="零件名称"></el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <el-table-column prop="amount" label="金额">
            <template #default="scope">
              ¥{{ scope.row.amount }}
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 工单明细 -->
      <template v-if="currentDetailType === 'repair'">
        <div class="repair-detail">
          <el-image
            v-if="repairDetail.problemImgUrls"
            style="width: 200px; height: 200px"
            :src="repairDetail.problemImgUrls.split(',')[0]"
            :preview-src-list="repairDetail.problemImgUrls.split(',')"
            fit="cover"
          />
          <div class="repair-info">
            <p><strong>故障描述：</strong>{{ repairDetail.problemDesc }}</p>
            <p><strong>维修预算金额：</strong>¥{{ repairDetail.budgetAmount }}</p>
            <p><strong>实际结算金额：</strong>¥{{ repairDetail.actualCost }}</p>
            <p><strong>故障单创建时间：</strong>{{ repairDetail.createTime }}</p>
            <p><strong>客户回访记录：</strong>{{ repairDetail.feedback }}</p>
          </div>
          <el-collapse>
            <el-collapse-item title="跟踪记录">
              <div v-for="(record, index) in repairDetail.repairSchedule" :key="index">
                <p><strong>工单状态：</strong>{{ record.orderStatus }}</p>
                <p><strong>跟踪记录时间：</strong>{{ record.traceDatetime }}</p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </template>

      <!-- 车辆信息 -->
      <template v-if="currentDetailType === 'vehicle'">
        <div class="vehicle-detail">
          <p><strong>品牌：</strong>{{ vehicleDetail.brand }}</p>
          <p><strong>车型：</strong>{{ vehicleDetail.model }}</p>
          <p><strong>车牌号：</strong>{{ vehicleDetail.plateNumber }}</p>
          <p><strong>当前里程数：</strong>{{ vehicleDetail.mileage }}km</p>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.repair-approve {
  padding: 0px;
}

.status-menu {
  margin-bottom: 20px;
}

.approve-table {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.repair-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.repair-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.vehicle-detail {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

:deep(.el-select) {
  width: 120px;
  margin-right: 10px;
}
</style>